﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Bingosoft.Components.DataDictionary;
using System.Data;
using Bingosoft.Data;

[assembly: WebResource("HHMMS.Core.Web.WebControls.Js.SmartCheckBox.js", "application/x-javascript")]
namespace HHMMS.Core.WebControls
{
    /// <summary>
    /// 与KissU字典组件兼容的CheckBoxList或者RadioButtonList控件。
    /// </summary>
    public class SmartCheckBox : CompositeControl
    {
        protected TextBox tbValues = new TextBox();

        /// <summary>
        /// 设置获取返回选择项的sqlId或sql命令。
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        public string CommandName { get; set; }

        /// <summary>
        /// 设置选择项关联的字典名称。
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        public string DictionaryCode { get; set; }

        /// <summary>
        /// 设置是水平呈现选择性还是垂直呈现选择项。
        /// </summary>
        [DefaultValue(RepeatDirection.Horizontal)]
        [PersistenceMode(PersistenceMode.Attribute)]
        public RepeatDirection RepeatDirection { get; set; }

        /// <summary>
        /// 设置是以CheckBox形式还是以RadioButton形式呈现待选择项。
        /// </summary>
        [DefaultValue(RenderMode.CheckBox)]
        [PersistenceMode(PersistenceMode.Attribute)]
        public RenderMode RenderMode { get; set; }

        /// <summary>
        /// 设置KissU前段js验证规则。
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        public string Validator { get; set; }

        /// <summary>
        /// 设置选择项的值关联的字段名称。
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        public string ValueField { get; set; }

        /// <summary>
        /// 每行显示的数目。
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        public int LineCount { get; set; }

        /// <summary>
        /// 获取或设置选择项的值。
        /// </summary>
        public string SelectedValue
        {
            get
            {
                return tbValues.Text;
            }
            set
            {
                tbValues.Text = value;
            }
        }

        /// <summary>
        /// 获取或设置选择项。
        /// </summary>
        public ListItemCollection Items { get; set; }

        /// <summary>
        /// 获取或设置待呈现的选择项。
        /// </summary>
        public List<ListItem> SelectedItems
        {
            get
            {
                var items = new List<ListItem>();
                if (string.IsNullOrEmpty(this.SelectedValue))
                    return items;

                var values = this.SelectedValue.Split(',');
                foreach (string val in values)
                {
                    var temp = this.Items.FindByValue(val);
                    if (temp != null)
                    {
                        items.Add(temp);
                    }
                }
                return items;
            }
            set
            {
                if (value != null)
                {
                    foreach (var item in value)
                    {
                        var temp = this.Items.FindByValue(item.Value);
                        if (temp != null)
                        {
                            temp.Selected = true;
                        }
                    }
                }
            }
        }

        protected override void CreateChildControls()
        {
            this.Controls.Clear();

            //创建选择项
            var selectedItems = this.SelectedItems;
            int index = 0;
            foreach (ListItem item in this.Items)
            {
                index++;
                if (this.RenderMode == WebControls.RenderMode.CheckBox)
                {
                    CheckBox checkBox = new CheckBox();
                    checkBox.ID = item.Value;
                    checkBox.Checked = selectedItems.Contains(item);
                    checkBox.Text = item.Text;
                    checkBox.TextAlign = TextAlign.Right;
                    checkBox.InputAttributes["value"] = item.Value;
                    this.Controls.Add(checkBox);
                }
                else
                {
                    RadioButton radio = new RadioButton();
                    radio.ID = item.Value;
                    radio.Checked = selectedItems.Contains(item);
                    radio.Text = item.Text;
                    radio.TextAlign = TextAlign.Right;
                    this.Controls.Add(radio);
                }

                //添加分隔符
                Literal split = new Literal();
                if (this.RepeatDirection == System.Web.UI.WebControls.RepeatDirection.Horizontal)
                {
                    if (this.LineCount > 0 && this.LineCount == index)
                    {
                        split.Text = "<br />";
                        index = 0;
                    }
                    else
                    {
                        split.Text = "&nbsp;&nbsp;&nbsp;";
                    }
                }
                else
                {
                    split.Text = "<br />";
                }
                this.Controls.Add(split);
            }

            //创建隐藏域用来保存选择的值
            tbValues.Text = this.SelectedValue;
            tbValues.ID = "SelectedValue";
            tbValues.Attributes["style"] = "display:block;position:absolute;left:0;top:0;border:0;z-index:-1;font-size:0;height:20px;background-color:transparent;";
            if (!string.IsNullOrEmpty(this.ValueField))
            {
                tbValues.Attributes["Name"] = this.ValueField;
            }
            if (!string.IsNullOrEmpty(this.Validator))
            {
                tbValues.Attributes["validator"] = this.Validator;
            }
            this.Controls.Add(tbValues);

            this.ClearChildViewState();
        }

        //初始化选择项
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.Items = new ListItemCollection();
            if (!string.IsNullOrEmpty(this.DictionaryCode))
            {
                IEnumerable<KeyValuePair<string, string>> lists = DataDictionaryFactory.DataDictionaryProvider.LookupDataDictionary(this.DictionaryCode);
                foreach (KeyValuePair<string, string> item in lists)
                {
                    this.Items.Add(new ListItem(item.Value, item.Key));
                }
            }
            else if (!string.IsNullOrEmpty(this.CommandName))
            {
                IDataReader reader = Dao.Get().QueryReader(this.CommandName, null);
                while (reader.Read())
                {
                    this.Items.Add(new ListItem(Convert.ToString(reader.GetValue(0)), Convert.ToString(reader.GetValue(1))));
                }
            }
        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            //设置CheckBox或者RadioButton的选中状态
            var selectedItems = this.SelectedItems;
            foreach (ListItem item in selectedItems)
            {
                var ctrl = this.FindControl(item.Value);
                if (ctrl != null)
                {
                    if (ctrl is CheckBox) (ctrl as CheckBox).Checked = true;
                    else if (ctrl is RadioButton) (ctrl as RadioButton).Checked = true;
                }
            }

            //引入脚本资源
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "HHMMS.Core.Web.WebControls.Js.SmartCheckBox.js");
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            writer.AddStyleAttribute("text-align", "left");
            writer.AddStyleAttribute("position", "relative");
            writer.AddStyleAttribute("z-index", "0");
            writer.AddAttribute("name", "smartCheck");

            base.RenderBeginTag(writer);
        }
    }

    /// <summary>
    /// 呈现模式。
    /// </summary>
    public enum RenderMode
    {
        /// <summary>
        /// 复选框。
        /// </summary>
        CheckBox,

        /// <summary>
        /// 单选按钮。
        /// </summary>
        RadioButton
    }
}
